<script setup lang="tsx">
import type { DataTableInst } from 'naive-ui';
import { NButton, NGradientText, NInput, NPopconfirm, useMessage } from 'naive-ui';
import { defineComponent, h, nextTick, ref } from 'vue';
import * as XLSX from 'xlsx';
import { fetchDeleteBatchDish, fetchDeleteDish, fetchEditDish, fetchGetAllDish } from '@/service/api';
import { $t } from '@/locales';
import { useAppStore } from '@/store/modules/app';
// import { enableStatusRecord, userGenderRecord } from '@/constants/business';
import { useTable, useTableOperate } from '@/hooks/common/table';
import UserOperateDrawer from './modules/user-operate-drawer.vue';
import UserSearch from './modules/user-search.vue';

const appStore = useAppStore();
const page = ref(1);
const message = useMessage();
const handlePageChange = curPage => {
  page.value = curPage;
};

const getDataIndex = key => {
  return data.value.findIndex(item => item.id === key);
};

const ShowOrEdit = defineComponent({
  props: {
    value: [String, Number],
    onUpdateValue: [Function, Array]
  },
  setup(props) {
    const isEdit = ref(false);
    const inputRef = ref(null);
    const inputValue = ref(props.value);
    function handleOnClick() {
      isEdit.value = true;
      nextTick().then(() => {
        inputRef.value.focus();
      });
    }
    function handleChange() {
      props.onUpdateValue(inputValue.value);
      isEdit.value = false;
    }
    function handleBlur() {
      isEdit.value = false;
    }
    return () =>
      h(
        'div',
        {
          style: 'min-height: 22px',
          onClick: handleOnClick
        },
        isEdit.value
          ? h(NInput, {
              ref: inputRef,
              value: inputValue.value,
              onUpdateValue: v => {
                inputValue.value = v;
              },
              onChange: handleChange,
              onBlur: handleBlur
            })
          : props.value
      );
  }
});
const { columns, columnChecks, data, getData, loading, mobilePagination, searchParams, resetSearchParams } = useTable({
  apiFn: fetchGetAllDish,
  apiParams: {
    current: 1,
    size: 10,
    // if you want to use the searchParams in Form, you need to define the following properties, and the value is null
    // the value can not be undefined, otherwise the property in Form will not be reactive
    status: null,
    userName: null,
    userGender: null,
    nickName: null,
    userPhone: null,
    userEmail: null
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'index',
      title: $t('common.index'),
      align: 'center',
      width: 64,
      resizable: true
    },
    // {
    //   key: 'id',
    //   title: $t('page.food.dish.id'),
    //   align: 'center',
    //   minWidth: 100
    // },
    {
      key: 'name',
      title(column) {
        return h(
          NGradientText,
          {
            size: '20',
            type: 'info'
          },
          { default: () => '菜品名称' }
        );
      },
      align: 'center',
      width: 100,
      defaultSortOrder: 'ascend',
      sorter: 'default',
      render(row) {
        const index = getDataIndex(row.id);
        return h(ShowOrEdit, {
          value: row.name,
          async onUpdateValue(v) {
            data.value[index].name = v;
            // 发起修改
            const datas = await fetchEditDish(row.id, data.value[index]);
            if (datas.error) {
              message.error(`修改订单菜品失败 ${datas.error.message}`);
            } else {
              message.success('修改菜单成功');
            }
            getData();
          }
        });
      }
    },
    // {
    //   key: 'title',
    //   title: $t('page.food.dish.title'),
    //   align: 'center',
    //   minWidth: 100
    // },
    {
      key: 'price',
      title(column) {
        return h(
          NGradientText,
          {
            size: '20',
            type: 'warning'
          },
          { default: () => '价格' }
        );
      },
      align: 'center',
      width: 120,
      sorter: (row1, row2) => row1.price - row2.price,
      render(row) {
        const index = getDataIndex(row.id);
        return h(ShowOrEdit, {
          value: row.price,
          async onUpdateValue(v) {
            data.value[index].price = Number(v);
            // 发起修改
            const datas = await fetchEditDish(row.id, data.value[index]);
            if (datas.error) {
              message.error(`修改订单菜品失败 ${datas.error.message}`);
            } else {
              message.success('修改菜单成功');
            }
            getData();
          }
        });
      }
    },
    {
      key: 'category',
      title: $t('page.food.dish.category'),
      align: 'center',
      width: 200,
      resizable: true,
      render(row) {
        const index = getDataIndex(row.id);
        return h(ShowOrEdit, {
          value: row.category,
          async onUpdateValue(v) {
            data.value[index].category = v;
            // 发起修改
            const datas = await fetchEditDish(row.id, data.value[index]);
            if (datas.error) {
              message.error(`修改订单菜品失败 ${datas.error.message}`);
            } else {
              message.success('修改菜单成功');
            }
            getData();
          }
        });
      }
    },
    // {
    //   key: 'picture',
    //   title: $t('page.food.dish.picture'),
    //   align: 'center',
    //   width: 100,
    //   render: row => {
    //     return <NTag>{row.picture}</NTag>;
    //   }
    // },
    {
      key: 'sale',
      title: $t('page.food.dish.sale'),
      align: 'center',
      width: 100,
      sorter: (row1, row2) => row1.sale - row2.sale,
      render(row) {
        const index = getDataIndex(row.id);
        return h(ShowOrEdit, {
          value: row.sale,
          async onUpdateValue(v) {
            data.value[index].sale = Number.parseFloat(v);
            // 发起修改
            const datas = await fetchEditDish(row.id, data.value[index]);
            if (datas.error) {
              message.error(`修改订单菜品失败 ${datas.error.message}`);
            } else {
              message.success('修改菜单成功');
            }
            getData();
          }
        });
      }
    },
    {
      key: 'description',
      title: $t('page.food.dish.description'),
      align: 'center',
      width: 100,
      render(row) {
        const index = getDataIndex(row.id);
        return h(ShowOrEdit, {
          value: row.description,
          async onUpdateValue(v) {
            data.value[index].description = v;
            // 发起修改
            const datas = await fetchEditDish(row.id, data.value[index]);
            if (datas.error) {
              message.error(`修改订单菜品失败 ${datas.error.message}`);
            } else {
              message.success('修改菜单成功');
            }
            getData();
          }
        });
      }
    },
    {
      key: 'short',
      title: '快捷键',
      align: 'center',
      width: 100,
      render(row) {
        const index = getDataIndex(row.id);
        return h(ShowOrEdit, {
          value: row.short,
          async onUpdateValue(v) {
            data.value[index].short = v;
            // 发起修改
            const datas = await fetchEditDish(row.id, data.value[index]);
            if (datas.error) {
              message.error(`修改订单菜品失败 ${datas.error.message}`);
            } else {
              message.success('修改菜单成功');
            }
            getData();
          }
        });
      }
    },
    {
      key: 'disabled',
      title: '是否禁用',
      align: 'center',
      width: 100,
      render(row) {
        return <NTag type={row.disabled === true ? 'error' : 'success'}>{row.disabled === true ? '是' : '否'}</NTag>;
      }
    },
    {
      key: 'recommend',
      title: '是否推荐',
      align: 'center',
      width: 100,
      render(row) {
        return <NTag type={row.recommend === true ? 'error' : 'success'}>{row.recommend === true ? '是' : '否'}</NTag>;
      }
    },
    {
      key: 'img',
      title: '图片',
      align: 'center',
      width: 100,
      render(row) {
        const index = getDataIndex(row.id);
        return h(ShowOrEdit, {
          value: row.img,
          async onUpdateValue(v) {
            data.value[index].img = v;
            // 发起修改
            const datas = await fetchEditDish(row.id, data.value[index]);
            if (datas.error) {
              message.error(`修改订单菜品失败 ${datas.error.message}`);
            } else {
              message.success('修改菜单成功');
            }
            getData();
          }
        });
      }
    },
    {
      key: 'message',
      title: $t('page.food.dish.message'),
      align: 'center',
      width: 100,
      render(row) {
        const index = getDataIndex(row.id);
        return h(ShowOrEdit, {
          value: row.message,
          async onUpdateValue(v) {
            data.value[index].message = v;
            // 发起修改
            const datas = await fetchEditDish(row.id, data.value[index]);
            if (datas.error) {
              message.error(`修改订单菜品失败 ${datas.error.message}`);
            } else {
              message.success('修改菜单成功');
            }
            getData();
          }
        });
      }
    },
    {
      key: 'times',
      title: $t('page.food.dish.times'),
      align: 'center',
      width: 200,
      render: row => {
        return row.times.split('+')[0];
      }
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 130,
      render: row => (
        <div class="flex-center gap-8px">
          <NButton type="primary" ghost size="small" onClick={() => edit(row.id)}>
            {$t('common.edit')}
          </NButton>
          <NPopconfirm onPositiveClick={() => handleDelete(row.id)}>
            {{
              default: () => $t('common.confirmDelete'),
              trigger: () => (
                <NButton type="error" ghost size="small">
                  {$t('common.delete')}
                </NButton>
              )
            }}
          </NPopconfirm>
        </div>
      )
    }
  ]
});

const {
  drawerVisible,
  operateType,
  editingData,
  handleAdd,
  handleEdit,
  checkedRowKeys,
  onBatchDeleted,
  onDeleted
  // closeDrawer
} = useTableOperate(data, getData);

async function handleBatchDelete() {
  // request
  const { error, data } = await fetchDeleteBatchDish(checkedRowKeys.value);
  if (!error) {
    window.$message?.success($t('common.deleteSuccess'));
    console.log(data);
  } else {
    window.$message?.error(error.message);
  }
  console.log(checkedRowKeys.value);

  onBatchDeleted();
}

async function handleDelete(id: number) {
  // request
  const { error, data } = await fetchDeleteDish(id);
  if (!error) {
    window.$message?.success($t('common.deleteSuccess'));
    console.log(data);
  } else {
    window.$message?.error(error.message);
  }
  console.log(id);

  onDeleted();
}

function edit(id: number) {
  handleEdit(id);
}

const tableRef = ref<DataTableInst>();
const downloadCsv = () => {
  tableRef.value?.downloadCsv({ fileName: 'Sheet1', keepOriginalData: true });
};
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <UserSearch v-model:model="searchParams" @reset="resetSearchParams" @search="getData" />
    <NCard :title="$t('route.food_caidan')" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          kind="dish"
          @add="handleAdd"
          @delete="handleBatchDelete"
          @refresh="getData"
          @download="downloadCsv"
        />
      </template>

      <NDataTable
        ref="tableRef"
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="large"
        :flex-height="!appStore.isMobile"
        :scroll-x="962"
        :loading="loading"
        remote
        :row-key="row => row.id"
        :pagination="mobilePagination"
        :on-update:page="handlePageChange"
        class="sm:h-full"
      />
      <UserOperateDrawer
        v-model:visible="drawerVisible"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="getData"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
